import { errorLogger, requestLogger } from './middlewares/logger'
import router from './routes/index'
import cors from './middlewares/cors'
import errorHandler from './middlewares/error'
import limit from './middlewares/rateLimiter'
import { MONGO_URL_DEV } from './utils/constants'
import express from 'express'
import mongoose from 'mongoose'
import { errors } from 'celebrate'
import helmet from 'helmet'
import path from 'path'
import {config} from 'dotenv'
import {fileURLToPath} from 'url'

config()
const { PORT = 3300 } = process.env
const { NODE_ENV, MONGO_URL } = process.env

const app = express()

mongoose.connect(NODE_ENV === 'production' ? MONGO_URL : MONGO_URL_DEV)
  .then(() => {
    console.log('Connected!')
  })
  .catch((error) => {
    console.log('No Connected!', error)
  })

app.use(express.json())
app.use(cors)

app.use(requestLogger)

app.get('/crash-test', () => {
  setTimeout(() => {
    throw new Error('Сервер сейчас упадёт')
  }, 0)
})

app.use(helmet())

const filename = fileURLToPath(import.meta.url);

const dirname = path.dirname(filename);

app.use(express.static(path.join(dirname, '../front-end/build')))

app.use(limit)

app.use(router)

app.use(errorLogger) // подключаем логгер ошибок

app.use(errors()) // обработчик ошибок celebrate

app.use(errorHandler)

app.listen(PORT, () => {
  console.log('Запуск сервера')
})
